package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.TaskRecord;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.core.entity.manage.AssetUse;
import com.joint.core.entity.manage.UseDetail;
import com.joint.core.service.UseDetailService;
import com.joint.core.service.AssetUseService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZhuChunXiao on 2017/3/29.
 */
@ParentPackage("manage")
public class AjaxUsedetailAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private AssetUseService assetUseService;
    @Resource
    private UseDetailService useDetailService;
    @Resource
    private TaskRecordService taskRecordService;

    /**
     * 原使用部门
     */
    private String oldDepartment;
    /**
     * 原使用人员
     */
    private String oldUser;
    /**
     * 新使用部门
     */
    private String newDepartmentId;
    /**
     * 新使用人员
     */
    private String newUserId;
    /**
     * 会签人员Id
     */
    private String examUsersId;

    private AssetUse assetUse;
    private UseDetail useDetail;
    private int numStatus;
    private Users loginUser;

    public String execute(){
        return "usedetail";
    }


    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            assetUse = assetUseService.get(parentId);
            params.put("assetUse",assetUse);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager= useDetailService.findByPagerAndLimit(true, "usedetail", pager, params);
        List<UseDetail> useDetailList;
        if (pager.getTotalCount() > 0){
            useDetailList = (List<UseDetail>) pager.getList();
        }else{
            useDetailList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(UseDetail useDetail : useDetailList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", useDetail.getId());
            rMap.put("oldDept", useDetail.getAssetUse().getDepartment().getName());
            rMap.put("oldUser", useDetail.getAssetUse().getUser().getName());
            rMap.put("newDept", useDetail.getNewDepartment().getName());
            rMap.put("newUser", useDetail.getNewUser().getName());
            rMap.put("state", useDetail.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            useDetail=useDetailService.get(keyId);
        }
        return "read";
    }

    public String input(){
        if(StringUtils.isNotEmpty(keyId)){
            useDetail=useDetailService.get(keyId);
            oldDepartment=useDetail.getAssetUse().getDepartment().getName();
            oldUser=useDetail.getAssetUse().getUser().getName();
        }
        if(StringUtils.isNotEmpty(parentId)){
            assetUse=assetUseService.get(parentId);
            oldDepartment=assetUse.getDepartment().getName();
            oldUser=assetUse.getUser().getName();
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            useDetail=useDetailService.get(keyId);
        }else{
            useDetail=new UseDetail();
            useDetail.setCreater(usersService.getLoginInfo());
        }
        useDetail.setNewDepartment(departmentService.get(newDepartmentId));
        useDetail.setNewUser(usersService.get(newUserId));
        useDetail.setAssetUse(assetUseService.get(parentId));
        useDetail.setCompany(usersService.getLoginInfo().getCompany());
        List<Users> usersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(examUsersId)){
            String[] idArr = examUsersId.split(",");
            for(String id:idArr){
                usersList.add(usersService.get(id.trim()));
            }
        }
        useDetail.setExamUsers(usersList);
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                useDetailService.update(useDetail);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                useDetailService.save(useDetail, "usedetail", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

//        List<Users> usersList = Lists.newArrayList();
        List<String> stringList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(examUsersId)){
            for(String id:examUsersId.split(",")){
//                usersList.add(usersService.get(id.trim()));
                stringList.add(id.trim());
            }
        }
        var1.put("approvers", stringList);
        var2.put("approvers", stringList);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                useDetailService.approve(useDetail, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = useDetailService.commit(useDetail, "usedetail", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //会签
    public String approve1(){
        useDetail = useDetailService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                useDetailService.approve(useDetail, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                UseDetail useDetail = useDetailService.get(keyId);
                useDetail.setProcessState(FlowEnum.ProcessState.Finished);
                useDetailService.update(useDetail);
                assetUse=useDetail.getAssetUse();
                assetUse.setDepartment(useDetail.getNewDepartment());
                assetUse.setUser(useDetail.getNewUser());
                assetUseService.update(assetUse);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(useDetail.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            useDetail = useDetailService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("usedetail");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            // System.out.println("comment:"+comment);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            useDetailService.reject(useDetail, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            useDetail = useDetailService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("usedetail");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            useDetailService.deny(useDetail, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }


    public String getNewDepartmentId() {
        return newDepartmentId;
    }

    public void setNewDepartmentId(String newDepartmentId) {
        this.newDepartmentId = newDepartmentId;
    }

    public String getNewUserId() {
        return newUserId;
    }

    public void setNewUserId(String newUserId) {
        this.newUserId = newUserId;
    }

    public String getExamUsersId() {
        return examUsersId;
    }

    public void setExamUsersId(String examUsersId) {
        this.examUsersId = examUsersId;
    }

    public AssetUse getAssetUse() {
        return assetUse;
    }

    public void setAssetUse(AssetUse assetUse) {
        this.assetUse = assetUse;
    }

    public UseDetail getUseDetail() {
        return useDetail;
    }

    public void setUseDetail(UseDetail useDetail) {
        this.useDetail = useDetail;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getOldDepartment() {
        return oldDepartment;
    }

    public void setOldDepartment(String oldDepartment) {
        this.oldDepartment = oldDepartment;
    }

    public String getOldUser() {
        return oldUser;
    }

    public void setOldUser(String oldUser) {
        this.oldUser = oldUser;
    }
}
